package cn.ctyun.videoplayer.widget;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.Toast;

import com.iheartradio.m3u8.Encoding;
import com.iheartradio.m3u8.Format;
import com.iheartradio.m3u8.PlaylistParser;
import com.iheartradio.m3u8.data.Playlist;
import com.iheartradio.m3u8.data.PlaylistData;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;

import cn.ctyun.videoplayer.bean.VideoModel;
import cn.ctyun.videoplayer.controller.MediaPlayerControlInterface;
import cn.ctyun.videoplayer.playerevent.PlayerEventInterface;
import cn.ctyun.videoplayer.util.HttpUtils;
import cn.ctyun.videoplayer.util.PlayerConstants;
import cn.ctyun.videoplayer.controller.AdController;
import cn.ctyun.videoplayer.controller.DanmakuController;
import cn.ctyun.videoplayer.util.SDKLog;
import okhttp3.Call;
import okhttp3.Response;

public class VideoView extends DefinitionIjkVideoView implements MediaPlayerControlInterface, PlayerEventInterface {

    private static final String TAG = VideoView.class.getSimpleName();

    protected int mCurrentVideoPosition = 0;//列表播放时当前播放视频的在List中的位置
    private boolean hasSetThumb = false;

    public VideoView(@NonNull Context context) {
        super(context);
    }

    public VideoView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public VideoView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public void onCompletion() {
        super.onCompletion();
        skipToNext();
    }

    @Override
    public void stop() {
        if (mVideos == null || mCurrentVideoPosition > mVideos.size() - 1) {
            return;
        }
        VideoModel videoModel = mVideos.get(mCurrentVideoPosition);
        if (PlayerConstants.VideoType.START_AD.equals(videoModel.getVideoType())
                || PlayerConstants.VideoType.END_AD.equals(videoModel.getVideoType())) {
            Toast.makeText(getContext(), "广告不支持停止播放", Toast.LENGTH_SHORT).show();
            return;
        }
        super.stop();
    }

    @Override
    public void stopStartAd() {
        if (mVideos == null || mCurrentVideoPosition > mVideos.size() - 1) {
            return;
        }
        VideoModel videoModel = mVideos.get(mCurrentVideoPosition);
        if (PlayerConstants.VideoType.START_AD.equals(videoModel.getVideoType())) {
            if (mCurrentVideoPosition + 1 == mVideos.size()) { // 已经最后一个，直接停止
                super.stop();
            } else {
                skipToNext();
            }
        }
    }

    @Override
    public void stopEndAd() {
        if (mVideos != null && mVideos.size() > 0) {
            if (mCurrentVideoPosition < mVideos.size()) {
                VideoModel videoModel = mVideos.get(mCurrentVideoPosition);
                if (PlayerConstants.VideoType.END_AD.equals(videoModel.getVideoType())) {
                    if (mCurrentVideoPosition + 1 == mVideos.size()) { // 已经最后一个，直接停止
                        super.stop();
                    } else {
                        skipToNext();
                    }
                }
            } else {
                super.stop();
            }
        }
    }

    /**
     * 重新播放
     */
    @Override
    public void retry() {
        mCurrentVideoPosition = 0;
        playNext(false);
        super.retry();
    }

    @Override
    protected void load() {
        super.load();
        if (mVideos != null && mVideos.size() > 0) {
            playNext(true);
        }
    }

    /**
     * 播放下一条视频
     */
    private void playNext(boolean firstPlay) {
        if (mVideos == null || mCurrentVideoPosition > mVideos.size() - 1) {
            return;
        }
        VideoModel videoModel = mVideos.get(mCurrentVideoPosition);

        if (videoModel != null) {
            mCurrentUrl = videoModel.getUrl();
            mCurrentVideoType = videoModel.getVideoType();
            mCurrentTitle = videoModel.getTitle();
            SDKLog.info(TAG, "playNext, url:" + mCurrentUrl);
            if (PlayerConstants.VideoType.START_AD.equals(videoModel.getVideoType())
                    || PlayerConstants.VideoType.END_AD.equals(videoModel.getVideoType())) {
                AdController adController = new AdController(getContext());
                if (hasSetThumb) {
                    adController.setThumbUrl(null);
                } else {
                    if (!TextUtils.isEmpty(mThumbUrl)) {
                        adController.setThumbUrl(mThumbUrl);
                        hasSetThumb = true;
                    }
                }
                adController.setFirstPlay(firstPlay);
                adController.setControllerListener(videoModel.getAdControllerListener());
                setVideoController(adController);
            } else {
                DanmakuController danmakuController = new DanmakuController(getContext());
                if (hasSetThumb) {
                    danmakuController.setThumbUrl(null);
                } else {
                    if (!TextUtils.isEmpty(mThumbUrl)) {
                        danmakuController.setThumbUrl(mThumbUrl);
                        hasSetThumb = true;
                    }
                }
                if (PlayerConstants.VideoType.LIVE.equals(videoModel.getVideoType())) {
                    danmakuController.setLive();
                }
                danmakuController.setFirstPlay(firstPlay);

                setVideoController(danmakuController);
                // m3u8多分辨率
                setVideoPath(videoModel.getUrl());
            }
        }
    }

    /**
     * 播放下一条视频，可用于跳过广告
     */
    @Override
    public void skipToNext() {
        mCurrentPosition = 0;
        mCurrentVideoPosition++;
        if (mVideos != null && mVideos.size() > 1) {
            if (mCurrentVideoPosition >= mVideos.size()) {
                super.stop();
            } else {
                playNext(false);
                addDisplay();
                startPrepare(true);
            }
        }
    }

    /**
     * Sets video path.
     *
     * @param path the path of the video.
     */
    public void setVideoPath(final String path) {
        if (TextUtils.isEmpty(path)) {
            return;
        }

        if (!path.startsWith("http:") && !path.startsWith("https:")){
            return;
        }

        HttpUtils.sendOkHttpRequest(path, new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "setVideoPath error :" + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String contentType = response.header("Content-Type");

                // 如果不是M3U8，则不处理
                if (TextUtils.isEmpty(contentType) || !contentType.toLowerCase().contains("x-mpegurl")) {
                    return;
                }

                if (response.body() == null) {
                    return;
                }
                String content = response.body().string();
                handleM3u8FileContent(path, content);
            }
        });
    }

    private void handleM3u8FileContent(String path, String content) {
        InputStream inputStream = new ByteArrayInputStream(content.getBytes());
        PlaylistParser parser = new PlaylistParser(inputStream, Format.EXT_M3U, Encoding.UTF_8);
        Playlist playlist = null;
        try {
            playlist = parser.parse();

        } catch (Exception e) {
            e.printStackTrace();
            Log.e("VideoView", e.getMessage());
        }

        if (playlist != null && playlist.hasMasterPlaylist()) {
            List<PlaylistData> playListData = playlist.getMasterPlaylist().getPlaylists();
            String[] splitUrl = path.split("/");
            String realUrl = "";
            for (int i = 0; i < splitUrl.length - 1; i++) {
                realUrl = realUrl + splitUrl[i] + "/";
            }

            List<PlaylistData> playlistDataList = new ArrayList<>();

            for (int i = 0; i < playListData.size(); i++) {

                if (!playListData.get(i).getUri().startsWith("http")) {

                    playlistDataList.add(new PlaylistData.Builder()
                            .withUri(realUrl + playListData.get(i).getUri())
                            .withStreamInfo(playListData.get(i).getStreamInfo())
                            .build());
                } else {
                    playlistDataList.add(playListData.get(i));
                }

            }

            getUrlList(playlistDataList);
        }
    }

    /**
     * 处理m3u8的多清晰度，按照带宽大小进行升序排序
     */
    public void getUrlList(List<PlaylistData> playlistDataList) {
        if (playlistDataList == null || playlistDataList.size() <= 0) {
            return;
        }

        LinkedHashMap<String, String> m3u8Videos = new LinkedHashMap<>();

        Collections.sort(playlistDataList, new Comparator<PlaylistData>() {
            @Override
            public int compare(PlaylistData t1, PlaylistData t2) {
                if (t1.getStreamInfo().getBandwidth() > t2.getStreamInfo().getBandwidth()) {
                    return 1;
                } else if (t1.getStreamInfo().getBandwidth() == t2.getStreamInfo().getBandwidth()) {
                    if (t1.getStreamInfo().getResolution().width > t2.getStreamInfo().getResolution().width) {
                        return 1;
                    } else if (t1.getStreamInfo().getResolution().width < t2.getStreamInfo().getResolution().width) {
                        return -1;
                    } else {
                        if (t1.getStreamInfo().getResolution().height > t2.getStreamInfo().getResolution().height) {
                            return 1;
                        } else if (t1.getStreamInfo().getResolution().height < t2.getStreamInfo().getResolution().height) {
                            return -1;
                        }
                    }
                    return 0;
                }
                return -1;
            }
        });
        for (int i = 0; i < playlistDataList.size(); i++) {
            PlaylistData playlistData = playlistDataList.get(i);

            String name = "";
            String[] split = playlistData.getUri().split("name=");
            if (split.length > 1) {
                name = split[split.length - 1];
                try {
                    name = URLDecoder.decode(name.substring(0, name.indexOf("&")), "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            // 如果为空，则取分辨率的高+"P"
            if (TextUtils.isEmpty(name)) {
                try {
                    int height = playlistData.getStreamInfo().getResolution().height;
                    name = height + "P";
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (TextUtils.isEmpty(name)) {
                if (i == 0) {
                    name = "流畅";
                } else if (i == 1) {
                    name = "标清";
                } else if (i == 2) {
                    name = "高清";
                } else {
                    name = "其他";
                }
            }

            m3u8Videos.put(name, playlistData.getUri());
        }

        if (m3u8Videos.size() > 0) {
            setDefinitionVideos(m3u8Videos);
        }
    }
}
